<template>
  <el-card class="m-l-5">
    <el-upload
      ref="el_upload"
      with-credentials
      :headers="headers"
      :list-type="listType"
      :action="uploadAction"
      :multiple="multiple"
      :limit="limit"
      :accept="accept"
      :drag="drag"
      :file-list="fileListData"
      :show-file-list="showFileList"
      :class="disable ? { hide: disable } : 'upload-demo'"
      :disabled="disable"
      :auto-upload="autoUpload"
      :on-exceed="handleExceed"
      :before-upload="handleBeforeUpload"
      :on-success="handleUpload"
    >
      <i v-if="listType == 'picture-card'" slot="default" class="el-icon-upload" />
      <el-button v-else size="small" type="primary">点击上传</el-button>
      <div v-if="tips" slot="tip" class="el-upload__tip">{{ tips }}</div>

      <div v-if="showFileList && listType == 'picture-card'" slot="file" slot-scope="{ file }">
        <span v-if="file.channel !== '1' && file.channel !== '3' && file.channel !== '4'">{{ file.originalFilename }}</span>
        <img
          v-if="file.channel === '1'"
          class="el-upload-list__item-thumbnail img-list-thumbnail"
          :src="getImageSrc(file.fileId)"
          :alt="file.originalFilename"
        >
        <video
          v-if="file.channel === '3' || file.channel === '4'"
          class="el-upload-list__item-thumbnail img-list-thumbnail"
          :src="getVideoSrc(file.fileId)"
        />
        <span class="el-upload-list__item-actions">
            <span style="font-size: 10px;display: block;">{{ file.originalFilename }}</span>
            <span
              v-if="file.channel === '1'"
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
            >
              <i class="el-icon-zoom-in" />
            </span>
            <span
              v-if="file.channel === '3' || file.channel === '4'"
              class="el-upload-list__item-preview"
              @click="handleVideoCardPreview(file)"
            >
              <i class="el-icon-zoom-in" />
            </span>
            <span
              class="el-upload-list__item-delete"
              @click="handleDownload(file)"
            >
              <i class="el-icon-download" />
            </span>
            <span
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
            >
              <i class="el-icon-delete" />
            </span>
          </span>
      </div>
    </el-upload>
    <pagination v-if="showPagination" v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getFileData" />

    <el-dialog :visible.sync="imageDialogVisible" :title="currentFile.originalFilename" fullscreen :append-to-body="true" :before-close="closeDialog">
      <div style="width: 100%; height: 100%; display:flex; justify-content: center;">
        <img width="auto" :src="getImageSrc(currentFile.path)" :alt="currentFile.originalFilename">
      </div>
    </el-dialog>
    <el-dialog :visible.sync="videoDialogVisible" :title="currentFile.originalFilename" fullscreen :append-to-body="true" :before-close="closeDialog">
      <video width="100%" height="auto" object-fill="fill" :src="getVideoSrc(currentFile.path)" controls="controls" />
    </el-dialog>
  </el-card>
</template>

<script>
import { deleteFile } from '@/api/tool/file'
import { getAuthenticationHeader } from '@/utils/store'

export default {
  name: 'FileViewer',
  props: {
    disable: {
      default: false,
      type: Boolean
    },
    action: {
      default: `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/upload`,
      type: String
    },
    multiple: {
      default: false,
      type: Boolean
    },
    limit: {
      default: 1,
      type: Number
    },
    accept: {
      default: '',
      type: String
    },
    fileSize: {
      default: '10M',
      type: String
    },
    drag: {
      default: false,
      type: Boolean
    },
    tips: {
      default: '',
      type: String
    },
    listType: {
      default: 'picture-card',
      type: String
    },
    fileData: {
      default: () => [],
      type: Array
    },
    tableQuery: {
      default: () => ({
        page: 1,
        limit: 20,
        total: 0
      }),
      type: Object
    },
    showFileList: {
      default: true,
      type: Boolean
    },
    showPagination: {
      default: true,
      type: Boolean
    },
    autoUpload: {
      default: true,
      type: Boolean
    }
  },
  data() {
    return {
      headers: getAuthenticationHeader(),
      currentFile: {
        originalFilename: '',
        path: ''
      },
      imageDialogVisible: false,
      videoDialogVisible: false
    }
  },
  computed: {
    uploadAction: function() {
      return this.$store.state.app.server_api + this.action
    },
    fileListData:{
      get() {
        return this.fileData
      },
      set(val) {
        return val
      }
    }
  },
  methods: {
    getImageSrc(key) {
      return this.$api.getImageSrc(key)
    },
    getVideoSrc(key) {
      return this.$api.getVideoSrc(key)
    },
    getFileData() {
      this.fileListData = []
      this.$emit('getFileData', this.tableQuery)
      this.fileListData = this.fileData
    },
    handlePictureCardPreview(file) {
      this.currentFile.originalFilename = file.originalFilename
      this.currentFile.path = file.fileId
      this.videoDialogVisible = false
      this.imageDialogVisible = true
    },
    handleVideoCardPreview(file) {
      this.currentFile.originalFilename = file.originalFilename
      this.currentFile.path = file.fileId
      this.imageDialogVisible = false
      this.videoDialogVisible = true
    },
    handleExceed(files, fileList) {
      this.$modal.msgWarning(`最多只能上传 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    emitInput(fileList) {
      const file_id_list = fileList.map(file_ => {
        return file_.fileId
      })
      this.$emit('input', file_id_list)
      this.getFileData()
    },
    handleBeforeUpload(file) {
      if (this.accept.length > 0) {
        const suffix = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
        if (this.accept.indexOf(suffix) === -1) {
          this.$modal.msgWarning(`只支持上传[${this.accept}]格式文件，请重新选择文件`)
          return false
        }
      }
      if (this.fileSize.length > 0) {
        let numberStr = ''
        let unitStr = ''
        this.fileSize.split('').forEach(item => {
          if (!isNaN(Number(item))) {
            numberStr = numberStr + item + ''
          } else {
            unitStr = unitStr + item
            unitStr = unitStr.toLowerCase()
          }
        })
        let totalSize = file.size
        let errMessage = ''
        switch(unitStr) {
          case 'g':
          case 'bg':
            totalSize = file.size / 1024 / 1024 / 1024
            break
          case 'm':
          case 'mb':
            totalSize = file.size / 1024 / 1024
            break
          case 'k':
          case 'kb':
            totalSize = file.size / 1024
            break
        }
        const isOverSize = totalSize > Number(numberStr)
        const sizeZero = totalSize === 0
        if (isOverSize) {
          this.$modal.msgWarning(`文件大小限制${this.fileSize}！`)
          return false
        }else if (sizeZero) {
          this.$modal.msgWarning('文件无内容！')
          return false
        }

        this.$modal.loading('上传中，请稍后。。。')
      }
      return true
    },
    handleUpload(response, file, fileList) {
      const fileId = response.param
      fileList.map((file_, index) => {
        if (file.name === file_.name) {
          file_.fileId = fileId
        }
        return file_
      })

      this.$modal.closeLoading()
      this.emitInput(fileList)
    },
    handleRemove(file) {
      deleteFile({ key: file.fileId }).then(response => {
        this.$modal.msgSuccess(response.msg)
        let fileData_ = this.$api.deepClone(this.fileData)
        fileData_.filter(file_ => {
          return file_.fileId != file.fileId
        })
        this.emitInput(fileData_)
      }).catch(e => {})
    },
    handleDownload(file) {
      window.location.href = encodeURI(this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/public/file/download/${file.fileId}`)
    },
    clearFileList() {
      this.$refs.el_upload.abort()
      this.$refs.el_upload.clearFiles()
    },
    closeDialog(done) {
      this.currentFile.originalFilename = ''
      this.currentFile.path = ''
      done()
    }
  }
}
</script>

<style scoped>
::v-deep .el-upload-dragger {
  height: 100% !important;
}


::v-deep .hide .el-upload--picture-card {
  display: none;
}

.img-list-thumbnail {
  position: absolute!important;
  height: -webkit-fill-available!important;
  width: -webkit-fill-available!important;
}
</style>
